<style lang="scss" scoped>
.management {
  width: 100%;
  margin: auto;
  display: flex;
  justify-content: center;
  padding: 0 20px;

  &-arrangement {
    margin-top: 50px;
    width: 100%;

    &-header {
      display: flex;

      &-form-inline {
        margin: 0 30px;
      }
    }

    &-list {
      border: 1px solid #dfe6ec;
    }

    &-block {
      text-align: left;
      width: 100%;
      display: flex;
    }

    &-formRef {
      &-box {
        display: flex;
        flex-direction: column;
        margin-bottom: 20px;

        .lable {
          width: 100px;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .signReset {
          cursor: pointer;
        }

        .signReset:hover {
          text-decoration: underline;
          color: #007bff;
        }

        .point {
          cursor: pointer;
        }

        .point:hover {
          text-decoration: underline;
          color: #007bff;
        }
      }
    }

    &-position {
      position: relative;
      // display: flex;

      &-tag {
        position: absolute;
        top: 0;
        left: 0;
        cursor: pointer;
        z-index: 9999;
      }

      &-right {
        width: 100%;

        &-content {
          .dialog-footer {
            text-align: center;

            .page {
              font-weight: 600;
              margin-bottom: 20px;
            }

            .btnUD {
              text-align: center;
            }
          }
        }
      }
    }

    .sign-position {
      height: 500px;
      overflow-y: scroll;
      border: 1px solid #000000;
    }

    .design_head {
      text-align: left;
      margin-top: 10px;

      .van-radio__label {
        span {
          color: red;
          font-weight: 800;
        }
      }
    }

  }
}</style>
<template>
  <div class="management">
    <div class="management-arrangement">
      <div class="management-arrangement-header">
        <div class="management-arrangement-header-warp">
          <div>
            <el-button text type="primary" icon="el-icon-plus" @click="newPosition()">
              新增协议
            </el-button>
            <el-button text type="danger" icon="el-icon-delete" :disabled="currentItem.length <= 0" @click="batchDeletion">
              批量删除
            </el-button>
          </div>
        </div>
        <el-form :inline="true" :model="form" class="management-arrangement-header-form-inline">
          <el-form-item label="协议名称">
            <el-input v-model="form.name" placeholder="请输入协议名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button type="danger" @click="resetSearchInfo">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="management-arrangement-list">
        <el-table :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" />
          <el-table-column label="协议名称" prop="name" align="center" />
          <el-table-column label="创建时间" prop="created_at" align="center" />
          <el-table-column label="最后修改时间" prop="updated_at" align="center" />
          <el-table-column label="协议文件" align="center">
            <template slot-scope="scope">
              <a :href="scope.row.file">
                <el-button plain circle type="primary" icon="el-icon-download" />
              </a>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button :class="{ displayNone: state != 'normal' }" circle plain type="primary" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)" />
              <el-button
                v-if="state != 'normal'"
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row, 'huifu')"
              >恢复</el-button>
              <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="management-arrangement-block">
        <Pagination :total="total" :limit="paginate" @pagination="handleCurrentChange" />
      </div>
      <el-dialog
        :close-on-click-modal="false"
        :title="type == 'add' ? '新增协议' : '修改协议'"
        :visible.sync="addDialogVisible"
        width="35%"
        center
        @close="closeAgree"
      >
        <el-form ref="formRef" label-position="left" label-width="80px">
          <div class="management-arrangement-formRef">
            <div class="management-arrangement-formRef-box">
              <el-form-item label="协议名称">
                <el-input
                  v-model="input"
                  style="width: 300px"
                  placeholder="请输入协议名称"
                />
              </el-form-item>
              <el-form-item label="上传协议">
                <el-upload
                  class="upload-demo"
                  :action="baseUrl + 'api/v1/upload/file'"
                  :data="dataObj"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :before-upload="beforeAvatarUpload"
                  :limit="1"
                  :file-list="fileList"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
                </el-upload>
              </el-form-item>
              <el-form-item label="点位设置">
                <div class="point" @click="reset()">
                  {{ open ? "重新设置签署点位" : "点击设置签署点位" }}
                </div>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel()">取 消</el-button>
          <el-button type="primary" @click="append()">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        v-loading="loading"
        :close-on-click-modal="false"
        title="协议预览"
        :visible.sync="protocoleDialogVisible"
        center
      >
        <div style="text-align: right">
          <el-button type="primary" @click="point()">保存</el-button>
        </div>
        <div class="management-arrangement-position">
          <div @mousedown="handleMoveIcon">
            <el-tag
              class="management-arrangement-position-tag"
              type="primary"
            ><i class="el-icon-edit-outline" />协议签署位置</el-tag>
          </div>
          <div class="management-arrangement-position-right">
            <div class="management-arrangement-position-right-content">
              <div id="pdf">
                <pdf
                  ref="pdfs"
                  :page="pageNum"
                  :src="pdfUrl"
                  @progress="loadedRatio = $event"
                  @num-pages="pageTotalNum = $event"
                />
              </div>
              <div slot="footer" class="dialog-footer">
                <div class="page" style="margin-top: 10px; color: #409eff">
                  {{ pageNum }} / {{ pageTotalNum }}
                </div>
                <div class="btnUD">
                  <el-button
                    round
                    type="info"
                    style="height: 30px; width: 80px; margin-right: 40px"
                    size="mini"
                    @click="prePage"
                  >上一页</el-button>
                  <el-button
                    round
                    type="info"
                    style="height: 30px; width: 80px"
                    size="mini"
                    @click="nextPage"
                  >下一页</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { agree, setUpAgree, modifyAgree, deleteAgree } from '@/api/agree'
import pdf from 'vue-pdf'
import { nextTick } from 'vue'
export default {
  components: {
    pdf,
    Pagination
  },
  data() {
    return {
      state: 'normal',
      list: [],
      type: 'add',
      addDialogVisible: false,
      input: '',
      value: '',
      fileList: [],
      dataObj: {
        folder: 'protocol'
      },
      total: 0,
      page: 1,
      lastPage: '',
      pageNum: 1, // 当前页
      pageTotalNum: 1, // 总页数
      pdfUrl: '',
      isRouterAlive: false,
      positionX: 0,
      positionY: 0,
      protocoleDialogVisible: false,
      open: false,
      axisX: 0,
      axisY: 0,
      loading: false,
      form: {
        name: ''
      },
      paginate: 10,
      currentItem: []
    }
  },
  created() {
    this.baseUrl = process.env.VUE_APP_UPLOAD
    this.getdata()
  },
  methods: {
    onSubmit() {
      this.getdata()
    },
    resetSearchInfo() {
      this.page = this.$options.data().page
      this.form.name = this.$options.data().form.name
      this.getdata()
    },
    // 多选
    handleSelectionChange(e) {
      this.currentItem = e.map(item => item.id)
      console.log(JSON.stringify(this.currentItem), 857857)
    },
    batchDeletion() {
      const data = {
        agree_id: JSON.stringify(this.currentItem)
      }
      deleteAgree(data)
      this.$confirm('是否删除', '提示', { type: 'warning' })
        .then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getdata()
        })
        .catch((err) => {})
    },
    handleMoveIcon(e) {
      console.log(this.$refs.pdfs)
      console.log(e)
      const pdf = document.getElementById('pdf')
      const w = pdf.offsetWidth
      const h = pdf.offsetHeight

      const odiv = e.target // 获取目标元素
      // 算出鼠标相对元素的位置
      const disX = e.clientX - odiv.offsetLeft
      const disY = e.clientY - odiv.offsetTop
      document.onmousemove = (e) => {
        // 鼠标按下并移动的事件
        // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        const left = e.clientX - disX
        const top = e.clientY - disY
        // 绑定元素位置到positionX和positionY上面
        // 移动当前元素
        if (left > 0 && left <= w - 106 && top > 0 && top <= h - 28) {
          odiv.style.left = left + 'px'
          odiv.style.top = top + 'px'
          const x = left / (w - 106)
          const y = top / (h - 28)
          this.axisX = parseFloat(x.toFixed(2))
          this.axisY = parseFloat(y.toFixed(2))
        }
      }
      document.onmouseup = (e) => {
        document.onmousemove = null
        document.onmouseup = null
      }
    },
    reset() {
      if (!this.fileList[0]) {
        return this.$message({
          type: 'info',
          message: '失败，请先上传协议'
        })
      }
      this.getpdf(this.fileList[0].path)
    },
    point() {
      this.protocoleDialogVisible = false
      this.open = true
      document.getElementsByClassName('management-arrangement-position-tag')[0].style.left = 0 + 'px'
      document.getElementsByClassName('management-arrangement-position-tag')[0].style.top = 0 + 'px'
    },
    getdata() {
      const data = {
        paginate: this.paginate,
        page: this.page,
        name: this.form.name
      }
      agree(data)
        .then((res) => {
          console.log(res, 666666)
          this.list = res.data
          this.total = res.meta.total
          this.lastPage = res.meta.last_page
        })
        .catch((err) => {
          console.log(err, 'err')
        })
    },
    prePage() {
      let page = this.pageNum
      page = page > 1 ? page - 1 : this.pageTotalNum
      this.pageNum = page
    },

    // 下一页
    nextPage() {
      let page = this.pageNum
      page = page < this.pageTotalNum ? page + 1 : 1
      this.pageNum = page
    },
    getpdf(file) {
      console.log(file)
      this.pdfUrl = pdf.createLoadingTask(file, {
        withCredentials: false
      })
      this.pdfUrl.promise
        .then((pdf) => {
          this.pageTotalNum = pdf.numPages
          this.reload()
          this.protocoleDialogVisible = true
          this.seat()
        })
        .catch((err) => {
          console.error('pdf 加载失败', err)
        })
    },
    seat() {
      this.$nextTick(() => {
        const pdfs = document.getElementById('pdf')
        const x = (pdfs.offsetWidth - 106) * this.axisX
        const y = (pdfs.offsetHeight - 28) * this.axisY
        document.getElementsByClassName('management-arrangement-position-tag')[0].style.left = x + 'px'
        document.getElementsByClassName('management-arrangement-position-tag')[0].style.top = y + 'px'
      })
    },
    reload() {
      this.isRouterAlive = false
      this.$nextTick(function() {
        this.isRouterAlive = true
      })
    },
    newPosition() {
      this.type = 'add'
      this.addDialogVisible = true
    },
    handleCurrentChange(e) {
      this.page = e.page
      this.paginate = e.limit
      this.getdata()
    },
    handleEdit(index, row) {
      console.log(row)
      this.type = 'edit'
      this.input = row.name
      this.agree_id = row.id
      this.axisX = row.x
      this.axisY = row.y
      this.value = row.file
      this.pageNum = row.page
      this.fileList.push({
        name: row.name,
        path: row.file
      })
      this.open = true
      this.addDialogVisible = true
    },
    handleDelete(index, row) {
      const agree_id = []
      agree_id.push(row.id)
      const data = {
        agree_id: JSON.stringify(agree_id)
      }
      deleteAgree(data)
      this.$confirm('是否删除', '提示', { type: 'warning' })
        .then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getdata()
        })
        .catch((err) => {})
    },
    cancel() {
      this.input = ''
      this.fileList = []
      this.addDialogVisible = false
    },
    closeAgree() {
      this.input = ''
      this.fileList = []
      this.pageNum = 0
      this.axisX = 0
      this.axisY = 0
      this.value = ''
      this.agree_id = ''
      this.addDialogVisible = false
      this.open = false
    },
    append() {
      if (!this.input) {
        this.$message({
          type: 'info',
          message: '失败，请输入协议名称'
        })
      }
      if (!this.value) {
        this.$message({
          type: 'info',
          message: '失败，请上传协议'
        })
      }
      if (!this.open) {
        this.$message({
          type: 'info',
          message: '失败，请先设置签署点位'
        })
      }
      if (this.open && this.value && this.input && this.type == 'add') {
        const data = {
          name: this.input,
          file: this.value,
          x: this.axisX,
          y: this.axisY,
          page: this.pageNum
        }
        setUpAgree(data)
          .then((res) => {
            this.$message({
              type: 'success',
              message: '新增成功'
            })
            this.getdata()
            this.addDialogVisible = false
          })
          .catch((err) => {})
      } else {
        const data = {
          name: this.input,
          file: this.value,
          x: this.axisX,
          y: this.axisY,
          page: this.pageNum,
          agree_id: this.agree_id
        }
        modifyAgree(data)
          .then((res) => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.getdata()
            this.addDialogVisible = false
          })
          .catch((err) => {})
      }
    },
    handleRemove(file, fileList) {
      this.fileList = []
      this.value = ''
    },
    handlePreview(file) {
      console.log(file)
    },
    beforeAvatarUpload(file) {
      console.log(file.type)
      const isJPG = file.type === 'application/pdf'

      if (!isJPG) {
        this.$message.error('上传协议文件只能是 pdf 格式!')
      }
      return isJPG
    },
    handleSuccess(file, fileList) {
      this.fileList.push({
        name: fileList.name,
        path: file.data.path
      })
      this.value = file.data.path
    }
  }
}
</script>

